<template>
  <common-layout>
    <div class="login-left animated fadeInLeft">
      <LogoSvg alt="logo" />
    </div>
    <div class="login-border animated fadeInRight">
      <div class="m-form">
        <div class="m-lang">
          <a-dropdown class="lang header-item">
            <div>
              <a-icon type="global"/>  {{langInfo.alias}}
            </div>
            <a-menu @click="val => setLang(val.key)" :selected-keys="[lang]" slot="overlay">
              <a-menu-item v-for=" lang in langList" :key="lang.key">{{lang.key.toLowerCase() + ' ' + lang.name}}</a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
        <div class="top">
          <div class="header">
            <img alt="logo" class="logo" src="@/assets/img/logo.png" />
            <span class="title">{{langInfo.systemName}}</span>
          </div>
          <div class="desc">{{langInfo.systemDesc}}</div>
        </div>
        <a-alert style="margin-bottom: 10px;" :message="$t('logintips')" type="success" />
        <div class="login">
          <a-form @submit="onSubmit" :form="form">
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon style="margin-bottom: 24px;" />
            <a-form-item>
              <a-input
                autocomplete="autocomplete"
                size="large"
                :placeholder="$t('loginname')"
                v-decorator="['name', {rules: [{ required: true, message: $t('loginname'), whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                :placeholder="$t('loginpwd')"
                autocomplete="autocomplete"
                type="password"
                v-decorator="['password', {rules: [{ required: true, message: $t('loginpwd'), whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input>
            </a-form-item>
            <div>
              <a-checkbox v-model="remember">{{$t('automatic')}}</a-checkbox>
              <a style="float: right">{{$t('pedreset')}}</a>
            </div>
            <a-form-item>
              <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit" type="primary">登录</a-button>
            </a-form-item>
            <div>
              {{$t('logway')}}
              <a-icon @click="qqLogin($t('qqlogin'))" class="icon" type="qq" />
              <a-icon @click="qqLogin($t('wechatlogin'))" class="icon" type="wechat" />
              <router-link style="float: right" to="/home" >{{$t('registered')}}</router-link>
            </div>
          </a-form>
        </div>
      </div>
    </div>
  </common-layout>
</template>

<script>
import LogoSvg from '@/assets/img/login.svg?inline'
import CommonLayout from '@/layouts/CommonLayout'
import {login, getMenuConfig} from '@/services/user/user'
import {setAuthorization} from '@/utils/request'
import {loadRoutes} from '@/utils/routerUtil'
import {mapState, mapMutations, mapGetters} from 'vuex'
import {getRsaCode} from '@/utils/util'

export default {
  name: 'Login',
  i18n: require('./i18n'),
  components: {CommonLayout,LogoSvg},
  data () {
    return {
      logging: false,
      error: '',
      remember: false,
      form: this.$form.createForm(this)
    }
  },
  computed: {
    ...mapState('setting', ['langList', 'lang']),
    ...mapGetters('account', ['loginInfo']),
    langInfo() {
      let lang = this.langList.find(item => item.key == this.lang)
      return lang
    }
  },
  mounted() {
    this.getUserCookie();
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setLoginInfo']),
    ...mapMutations('setting', ['setLang']),
    onSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          login(this.form.getFieldValue('name'), getRsaCode(this.form.getFieldValue('password'))).then(this.afterLogin)
        }
      })
    },
    afterLogin(res) {
      this.logging = false
      const loginRes = res.data
      if(loginRes.statusCode === 200){
        //记住密码
        if(this.remember){
          this.setLoginInfo({name:this.form.getFieldValue('name'), password:this.form.getFieldValue('password'), expire: new Date().getTime() + process.env.VUE_APP_USER_LOGIN_EXPIRE_KEY * 60 * 60 * 1000})
        }else{
          localStorage.removeItem(process.env.VUE_APP_USER_LOGIN_KEY)
        }
        
        const {userInfo, permissions} = loginRes.data
        this.setUser(userInfo)
        this.setPermissions(permissions)
        var date = new Date();
        date.setDate(date.getDate() + userInfo.tokenExpireAt);
        setAuthorization({token: userInfo.accessToken, expireAt: date})

        // 获取路由配置
        getMenuConfig().then(result => {
          if(result.status === 200){
            const routesConfig = result.data.data
            loadRoutes(routesConfig)
            this.$router.push('/dashboard/workplace')
            this.$message.success(`${userInfo.nickname}，欢迎回来`, 3)
          } else{
            this.error = result.errors
          }
        })
      } else {
        this.error = loginRes.errors
      }
    },
    qqLogin(text){
      this.$message.success(text, 3)
    },
    getUserCookie(){
      if(this.loginInfo){
        this.remember = true
        this.form.setFieldsValue({
          name: this.loginInfo.name,
          password: this.loginInfo.password,
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .common-layout{
    overflow: hidden;
    @media screen and (max-width:1000px) {
      background: url('../../assets/img/login.svg');
    }
    .login-left {
      @media screen and (max-width:1000px) {
        display: none;
      }
      float: left;
      width: 50%;
      position: relative;
      text-align: right;
    }
    .login-border {
      @media screen and (max-width:1000px) {
        width: 100%;
        height: 100%;
        margin: 0;
        display:flex;
        align-items:center;
        justify-content: center;
      }
      float: left;
      width: 45%;
      position: relative;
      margin-left: 5%;
      margin-top: 0rem;
      .m-form {
        @media screen and (max-width:1000px) {
          width: 458px;
          padding: 50px;
        }
        width: 408px;
        padding: 10px 20px 20px;
        box-shadow: 0 3px 12px rgba(0,0,0,.1);
        background: white;
        .m-lang {
          height: 25px;
          line-height: 25px;
          .lang {
            float: right;
            width: 5rem;
            text-align: right;
          }
        }
        .top {
          .header {
            height: 44px;
            line-height: 44px;
            a {
              text-decoration: none;
            }
            .logo {
              height: 44px;
              vertical-align: top;
              margin-right: 16px;
            }
            .title {
              font-size: 33px;
              color: @title-color;
              font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
              font-weight: 600;
              position: relative;
              top: 2px;
            }
          }
          .desc {
            font-size: 14px;
            color: @text-color-second;
            margin-top: 12px;
            margin-bottom: 20px;
          }
        }
        .login{
          @media screen and (max-width: 576px) {
            width: 95%;
          }
          @media screen and (max-width: 320px) {
            .captcha-button{
              font-size: 14px;
            }
          }
          .icon {
            font-size: 24px;
            color: @text-color-second;
            margin-left: 16px;
            vertical-align: middle;
            cursor: pointer;
            transition: color 0.3s;

            &:hover {
              color: @primary-color;
            }
          }
        }
      }
    }
  }
</style>
